import appConfig from '@/app.config';
import { ProductInfo } from '@/lib/dianxiaomi';
import { GigaProductInfo } from '@/lib/giga';
import { getProductTitle } from '@/lib/postme';
import { useSettingsStore } from '@/store';

export function usePostme() {
  const processSettings = useSettingsStore((state) => state.processSettings);
  async function generateProductName(
    gigaProductInfo: GigaProductInfo,
    skuIdInfoDirectoryHandle: FileSystemDirectoryHandle,
    directoryHandle: FileSystemDirectoryHandle,
  ) {
    const title = await getProductTitle({
      name: processSettings.generatorTitleName || directoryHandle.name,
      advantage: gigaProductInfo.feature || [],
      keyWord: gigaProductInfo.productName,
    });
    console.log('自动生成的 title', title, processSettings);
    // 保存到本地
    const productInfoFilename = appConfig.productInfoFilename;
    const fileHandle = await skuIdInfoDirectoryHandle.getFileHandle(productInfoFilename, {
      create: true,
    });
    const file = await fileHandle.getFile();
    let newContent = '';
    if (file.size === 0) {
      newContent = JSON.stringify({
        productName: title,
      });
    } else {
      const text = await file.text();
      const productInfoSettings: ProductInfo = JSON.parse(text);
      productInfoSettings.productName = title;
      newContent = JSON.stringify(productInfoSettings);
    }
    const fileWriter = await fileHandle.createWritable();
    await fileWriter.write(newContent);
    await fileWriter.close();
  }
  return {
    generateProductName: useCallback(generateProductName, [processSettings]),
  };
}
